﻿(function () {
    try {
        var capacity = [25, 15, 10, 10, 0, 80, 50, 50, 0, 0, 100, 0];

        var doc = document;
        if (window.frames.length > 0) doc = window.main.document;
        var url = document.URL;
        if (url.indexOf('screen=place') == -1) {
            alert('This script needs to be run from the rally point');
            return;
        }

        if (localStorage['uberfarmFarms']) config.farms = localStorage['uberfarmFarms'];

        var currentTime = (doc.getElementById('serverDate').firstChild.nodeValue + ' ' + doc.getElementById('serverTime').firstChild.nodeValue).match(/\d+/g);
        var currentTime = new Date(currentTime[2], currentTime[1] - 1, currentTime[0], currentTime[3], currentTime[4], currentTime[5]).getTime();

        var node = doc.forms[0].textContent;
        var openParen = 0;
        var closedParen = 0;
        var troopCount = {};
        var totalCap = 0;

        var troops = ['spear', 'sword', 'axe', 'archer', 'spy', 'light', 'marcher', 'heavy', 'ram', 'catapult'];

        for (i = 0; i < troops.length; i++) {
            var troop = parseInt(document.units[troops[i]].parentNode.getElementsByTagName('a')[1].innerHTML.match(/\d+/), 10);

            troopCount[i] = parseInt(troop);
            if (troopCount[i] < 12) {
                troopCount[i] = 0;
            }
            totalCap += troopCount[i] * capacity[i];
        }

        var goal, remainder, loads;
        if (totalCap < config.minHaul) {
            setTimeout(function () {
                window.close();
            }, 500);
            return;
        }
        else {
            goal = config.targetHaul;
            remainder = totalCap % goal;
            if (remainder != 0) {
                loads = Math.floor(totalCap / goal);
                if (remainder / loads <= (goal - remainder) / (loads + 1)) goal += remainder / loads;
                else {
                    loads++;
                    goal = totalCap / loads;
                }
            } else {
                loads = totalCap / goal;
            }
        }
        var node = document.getElementById('menu_row2').getElementsByTagName('b')[0];
        var coords = node.innerHTML.substring(1, 8);

        var cVil = {};
        cVil.x = parseInt(coords.split('|')[0]);
        cVil.y = parseInt(coords.split('|')[1]);

        var options = [];
        var data = config.farms.split(' ');

        for (var a = 0; a < data.length; a++) {
            var d = data[a].split('|');
            var x = Math.abs(parseInt(d[0]) - cVil.x);
            var y = Math.abs(parseInt(d[1]) - cVil.y);
            var dist = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
            if (dist <= config.fields) options.push({
                coords: data[a],
                distance: dist
            });
        }
        options.sort(function (a, b) {
            return a.distance - b.distance;
        });

        if (options.length == 0) {
            alert('There are no farms in range of this village');
            return;
        }

        var prospect = [];
        var target = -1;
        var store = 0;
        if (localStorage['uberfarmData']) { store = localStorage['uberfarmData']; }


        if (store.length == 0) {
            var target = 0;
            var preCookie = "",
                postCookie = "";
        }
        else {
            for (var a = 0; a < options.length; a++) {
                index = store.indexOf(options[a].coords);
                if (index == -1) {
                    var target = a;
                    var preCookie = store + "_",
                        postCookie = "";
                    break;
                } else {
                    var preCookie = store.substring(0, index);
                    var tcookie = store.substring(index);
                    var index = tcookie.indexOf("_");
                    if (index != -1) {
                        var postCookie = tcookie.substring(index);
                        tcookie = tcookie.substring(0, index);
                    } else var postCookie = "";
                    var lastTime = parseInt(tcookie.substring(tcookie.indexOf(":") + 1));
                    var deltaTime = currentTime - lastTime;
                    if (deltaTime > config.hours * 60 * 60 * 1000) {
                        var target = a;
                        break;
                    } else prospect.push({
                        deltaTime: deltaTime,
                        target: a,
                        preCookie: preCookie,
                        postCookie: postCookie
                    });
                }
            }
        }
        if (target == -1) {
            prospect.sort(function (a, b) {
                return b.deltaTime - a.deltaTime;
            });
            var target = prospect[0].target;
            preCookie = prospect[0].preCookie;
            postCookie = prospect[0].postCookie;
        }
        if (timers.length > 0) timers = [];
        var target = options[target].coords;
        var targetCoords = target.split('|');
        doc.forms[0].x.value = targetCoords[0];
        doc.forms[0].y.value = targetCoords[1];


        var fields = [
        document.forms[0].spear,
        document.forms[0].sword,
        document.forms[0].axe,
        document.forms[0].archer,
        document.forms[0].spy,
        document.forms[0].light,
        document.forms[0].marcher,
        document.forms[0].heavy,
        document.forms[0].ram,
        document.forms[0].catapult,
        document.forms[0].knight,
        document.forms[0].snob
        ];
        goal = config.targetHaul;

        var troopOrder = [1, 0, 2, 3, 6, 7, 5, 10];
        var count = 0;

        for (var i = 0; i < troopOrder.length && count < goal; i++) {

            var j = troopOrder[i];
            if (!troopCount[j]) continue;
            var troops = Math.ceil((goal - count) / capacity[j]);
            if (troops > troopCount[j]) troops = troopCount[j];
            count += capacity[j] * troops;
            fields[j].value = troops;
        }

        if (config.rams && troopCount[8] >= config.rams) {
            var rams = 0,
                i = loads;
            while (rams < config.rams && i > 0) {
                rams = Math.floor(troopCount[8] / i);
                i--;
            }
            fields[8].value = rams;
        }
        if (config.cats && troopCount[9] >= config.cats) {
            var cats = 0,
                i = loads;
            while (cats < config.cats && i > 0) {
                cats = Math.floor(troopCount[9] / i);
                i--;
            }
            fields[9].value = cats;
        }
        if (troopCount[4] > 3 && config.scout) {
            document.forms[0].spy.value = 1;
        }


        var store = preCookie + target + ":" + currentTime + postCookie;
        localStorage['uberfarmData'] = store;
    }
    catch (e) {
        alert(e);
    }
})();




/* original--->

(function () {

    /*Fixed by Stotty2009
    Don't try and pass my fix off as yours

    New Launch: LIVE version

    javascript: var config = {
    fields: 8000,
    minHaul: 20000,
    targetHaul: 40000,
    scout: true,
    hours: 24,
    farms: '443|167 450|167 453|167 444|168 450|168 455|168 456|168 443|169 445|169 446|169 449|169 452|169 454|169 443|170 447|170 450|170 451|170 452|170 455|170 444|171 445|171 448|171 451|171 452|171 444|172 448|172 455|172 456|172 444|173 445|173 448|173 449|173 454|173 443|174 445|174 447|174 451|174 452|174 454|174 455|174 453|175 445|176 446|176 448|176 450|176 451|176 452|176 453|176 443|177 444|177 449|177 453|177 447|178 448|178 449|178 453|178 444|179 451|179 457|179 445|180 447|180 454|180 450|181 452|181 454|181 455|181 456|181'
    };
    $.getScript('http://dl.dropbox.com/u/24469843/Tribalwars/Scripts/uberfarmNonArcherWorld.js');
    void (0);


    */
    /*var tw = [["en55", 1830], ["en55", 2005]];
    if (tw.length > 0) {
    for (x = 0; x < tw.length; x++) {
    if (game_data.world == tw[x][0] && game_data.player.ally_id == tw[x][1]) {
    alert("You can't use this script...Please contact Stotty2009 on skype to discuss this matter");
    window.close();
    }
    }
    }*
    try {
        var capacity = [25, 15, 10, 10, 0, 80, 50, 50, 0, 0, 100, 0];

        var doc = document;
        if (window.frames.length > 0) doc = window.main.document;
        var url = document.URL;
        if (url.indexOf('screen=place') == -1) {
            alert('This script needs to be run from the rally point');
            return;
        }

        if (localStorage['uberfarmFarms']) config.farms = localStorage['uberfarmFarms'];

        var currentTime = (doc.getElementById('serverDate').firstChild.nodeValue + ' ' + doc.getElementById('serverTime').firstChild.nodeValue).match(/\d+/g);
        var currentTime = new Date(currentTime[2], currentTime[1] - 1, currentTime[0], currentTime[3], currentTime[4], currentTime[5]).getTime();

        var node = doc.forms[0].textContent;
        var openParen = 0;
        var closedParen = 0;
        var troopCount = {};
        var totalCap = 0;

        var troops = ['spear', 'sword', 'axe', 'archer', 'spy', 'light', 'marcher', 'heavy', 'ram', 'catapult'];

        for (i = 0; i < troops.length; i++) {
            var troop = parseInt(document.units[troops[i]].parentNode.getElementsByTagName('a')[1].innerHTML.match(/\d+/), 10);

            troopCount[i] = parseInt(troop);
            if (troopCount[i] < 12) {
                troopCount[i] = 0;
            }
            totalCap += troopCount[i] * capacity[i];
        }

        var goal, remainder, loads;
        if (totalCap < config.minHaul) {
            setTimeout(function () {
                window.close();
            }, 500);
            return;
        }
        else {
            goal = config.targetHaul;
            remainder = totalCap % goal;
            if (remainder != 0) {
                loads = Math.floor(totalCap / goal);
                if (remainder / loads <= (goal - remainder) / (loads + 1)) goal += remainder / loads;
                else {
                    loads++;
                    goal = totalCap / loads;
                }
            } else {
                loads = totalCap / goal;
            }
        }
        var node = document.getElementById('menu_row2').getElementsByTagName('b')[0];
        var coords = node.innerHTML.substring(1, 8);

        var cVil = {};
        cVil.x = parseInt(coords.split('|')[0]);
        cVil.y = parseInt(coords.split('|')[1]);

        var options = [];
        var data = config.farms.split(' ');

        for (var a = 0; a < data.length; a++) {
            var d = data[a].split('|');
            var x = Math.abs(parseInt(d[0]) - cVil.x);
            var y = Math.abs(parseInt(d[1]) - cVil.y);
            var dist = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
            if (dist <= config.fields) options.push({
                coords: data[a],
                distance: dist
            });
        }
        options.sort(function (a, b) {
            return a.distance - b.distance;
        });

        if (options.length == 0) {
            alert('There are no farms in range of this village');
            return;
        }

        var prospect = [];
        var target = -1;
        var store = localStorage['uberfarmData'] || "";


        if (store.length == 0) {
            var target = 0;
            var preCookie = "",
                postCookie = "";
        }
        else {
            for (var a = 0; a < options.length; a++) {
                index = store.indexOf(options[a].coords);
                if (index == -1) {
                    var target = a;
                    var preCookie = store + "_",
                        postCookie = "";
                    break;
                } else {
                    var preCookie = store.substring(0, index);
                    var tcookie = store.substring(index);
                    var index = tcookie.indexOf("_");
                    if (index != -1) {
                        var postCookie = tcookie.substring(index);
                        tcookie = tcookie.substring(0, index);
                    } else var postCookie = "";
                    var lastTime = parseInt(tcookie.substring(tcookie.indexOf(":") + 1));
                    var deltaTime = currentTime - lastTime;
                    if (deltaTime > config.hours * 60 * 60 * 1000) {
                        var target = a;
                        break;
                    } else prospect.push({
                        deltaTime: deltaTime,
                        target: a,
                        preCookie: preCookie,
                        postCookie: postCookie
                    });
                }
            }
        }
        if (target == -1) {
            prospect.sort(function (a, b) {
                return b.deltaTime - a.deltaTime;
            });
            var target = prospect[0].target;
            preCookie = prospect[0].preCookie;
            postCookie = prospect[0].postCookie;
        }
        if (timers.length > 0) timers = [];
        var target = options[target].coords;
        var targetCoords = target.split('|');
        doc.forms[0].x.value = targetCoords[0];
        doc.forms[0].y.value = targetCoords[1];


        var fields = [
        document.forms[0].spear,
        document.forms[0].sword,
        document.forms[0].axe,
        document.forms[0].archer,
        document.forms[0].spy,
        document.forms[0].light,
        document.forms[0].marcher,
        document.forms[0].heavy,
        document.forms[0].ram,
        document.forms[0].catapult,
        document.forms[0].knight,
        document.forms[0].snob
        ];
        goal = config.targetHaul;

        var troopOrder = [1, 0, 2, 3, 6, 7, 5, 10];
        var count = 0;

        for (var i = 0; i < troopOrder.length && count < goal; i++) {

            var j = troopOrder[i];
            if (!troopCount[j]) continue;
            var troops = Math.ceil((goal - count) / capacity[j]);
            if (troops > troopCount[j]) troops = troopCount[j];
            count += capacity[j] * troops;
            fields[j].value = troops;
        }

        if (config.rams && troopCount[8] >= config.rams) {
            var rams = 0,
                i = loads;
            while (rams < config.rams && i > 0) {
                rams = Math.floor(troopCount[8] / i);
                i--;
            }
            fields[8].value = rams;
        }
        if (config.cats && troopCount[9] >= config.cats) {
            var cats = 0,
                i = loads;
            while (cats < config.cats && i > 0) {
                cats = Math.floor(troopCount[9] / i);
                i--;
            }
            fields[9].value = cats;
        }
        if (troopCount[4] > 3 && config.scout) {
            document.forms[0].spy.value = 1;
        }


        var store = preCookie + target + ":" + currentTime + postCookie;
        localStorage['uberfarmData'] = store;
    }
    catch (e) {
        alert(e);
    }
})();

*/